"""
本文件定义了一些与界面连接的接口
"""
#将文字转为图片形式
from PIL import Image, ImageFont, ImageDraw, ImageOps
import random
import numpy as np
import os

def smooth(image):  # 模糊图片
    w, h, c = image.shape
    smoothed_image = np.zeros([w - 2, h - 2, c])
    smoothed_image += image[:w - 2, 2:h, :]
    smoothed_image += image[1:w - 1, 2:, :]
    smoothed_image += image[2:, 2:h, :]
    smoothed_image += image[:w - 2, 1:h - 1, :]
    smoothed_image += image[1:w - 1, 2:h, :]
    smoothed_image += image[2:, 1:h - 1, :]
    smoothed_image += image[:w - 2, :h - 2, :]
    smoothed_image += image[1:w - 1, :h - 2, :]
    smoothed_image += image[2:, :h - 2, :]
    smoothed_image /= 9.0
    return smoothed_image.astype("uint8")

def char_to_picture(data_style, text="",  in_meddium=True, reverse_color=False, smooth_times=0, noise=0):
    if data_style == "Fonts100":
        background_color = (0, 0, 0)
        text_color = (255, 0, 0)
        font_size = 500
        pictrue_size = 600
        font_name = "DENG.ttf"
    else:
        background_color = (255, 255, 255)
        text_color = (0, 0, 0)
        font_size = 200
        pictrue_size = 320
        font_name = "SIMHEI.ttf"
    text_position = (0, 0)
    pictrue_shape = (pictrue_size, pictrue_size)
    im = Image.new("RGB", pictrue_shape, background_color)
    dr = ImageDraw.Draw(im)

    # 取得字体文件的位置
    font_dir = "C:\Windows\Fonts\\" + font_name
    font = ImageFont.truetype(font_dir, font_size)

    # 开始绘图,如果设置了居中，那么就居中,英文字母的对齐方式并不一样
    char_dict = []
    for i in range(26):
        char_dict.append(chr(i + ord('a')))
        char_dict.append(chr(i + ord('A')))
    if in_meddium:
        char_num = len(text)
        text_position = (pictrue_shape[0] / 2 - char_num * font_size / 2, pictrue_shape[1] / 2 - font_size / 2)  # 中文
        if text in char_dict:
            text_position = (
                pictrue_shape[0] / 2 - char_num * font_size / 4, pictrue_shape[1] / 2 - font_size / 2)  # 英文

    # 开始绘制图像
    dr.text(text_position, text, font=font, fill=text_color)
    if reverse_color:
        im = ImageOps.invert(im)

    # 随机扰动
    if noise > 0:
        print("adding noise...")
        im_array = np.array(im)
        noise_num = noise * pictrue_size
        for i in range(noise_num):
            pos = (random.randint(0, pictrue_size - 1), random.randint(0, pictrue_size - 1))
            color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
            im_array[pos[0], pos[1], :] = color
        im = Image.fromarray(im_array)

    # 模糊化图片
    im_array = np.array(im)
    for i in range(smooth_times):
        im_array = smooth(im_array)
    im = Image.fromarray(im_array)

    # 图片经过模糊后略有缩小
    im = im.resize(pictrue_shape)
    save_path = 'Style_Transfer/testimgs/' + data_style + '/' + data_style + '_sources/' + text + '.jpg'
    im.save(save_path)
    print("文字转换图片成功")

def change_character_line(text_line, data_style): #对多个文字进行处理
    for i in range(len(text_line)):
        text = text_line[i]
        char_to_picture(data_style, text)
    return True

def change_photo(path):
    name_suffix = path.split('/')[-1].split("\\")[0]
    save_path = 'Style_Transfer/testimgs/TextEffects/TextEffects_sources/' + name_suffix
    img = Image.open(path)
    im = img.convert('1')#非黑即白
    im.save(save_path)
    print("处理输入图像成功")
    return True

def read_output_path(data_style):#读取输出的图像的路径
    dir_path = 'Style_Transfer/testresults/' + data_style + '/' + data_style + '/test_latest/images/'
    file_name = [f for f in os.listdir(dir_path)]
    path_list = [] #保存处理后图片的相对路径
    for f in file_name:
        if 'transfered' in f:
            path_list.append(dir_path + f)
    return path_list #数组的形式，其中每一个元素就是一个输出结果的路径

def get_output_img(data_style):
    path_list = read_output_path(data_style)
    save_path = 'Style_Transfer/output_img/'
    for p in path_list:
        name_suffix = p.split('/')[-1].split("\\")[0]
        p_save_path = save_path + name_suffix
        p_read_path =  'Style_Transfer/testresults/' + data_style + '/' + data_style + '/test_latest/images/' + name_suffix
        if data_style == 'Fonts100':
            img = transPNG(p_read_path)
        else:
            img = Image.open(p)
        img.save(p_save_path)

def transPNG(srcImageName):
    img = Image.open(srcImageName)
    img = img.convert('RGBA')
    datas = img.getdata()
    newData = list()
    for item in datas:
        # print(item)
        # break
        if item[0] > 200:
            newData.append(item)
        else:
            newData.append((item[0], item[1], item[2], 0))
    img.putdata(newData)
    return img

def change_color(path, color_tuple):
    img = Image.open(path)
    img = img.convert('RGBA')
    datas = img.getdata()
    newData = list()
    for item in datas:
        if item[3] != 0:
            newData.append(color_tuple)
        else:
            newData.append(item)
    img.putdata(newData)
    img.save(path)


#*********************测试****************************
# change_character_line('真棒','TextEffects')
# a = read_output_path('Fonts100')
# print(a)